import React, { useState } from "react"
import ReactDOM from 'react-dom/client'
import Table from './components/FlowTask'
import MonacoEditor, { loader } from '@monaco-editor/react'
import { Button, message } from 'antd'

loader.config({ paths: { vs: "/monaco-editor@0.30.1/min/vs" } });

function App() {
  const [menu] = useState(JSON.decode(window.LOW_CODE_MENU))
  const [json, setJSON] = useState(JSON.decode(window.LOW_CODE_SCHEMA))

  const haddleKeyDown = (event) => {
    if(event.key === "s" && (event.ctrlKey || event.metaKey)) {
      save()
      event.preventDefault()
    }
  }

  const getPostUrl = () => '/api/menu/editor/' + menu.key  + "?type=FlowTask"

  const save = async() => {
    request.post(getPostUrl(), json).then(function(data) {
      message.success('保存成功')
    }).catch(e=>{
      message.error(e.statusText)
      console.log(e, json)
    })
  }


  let time = null
  const onchange = (code) => {
    clearTimeout(time)
    time = setTimeout(()=>{
      try {
        const execute = {
          ...json,
          config: JSON.executeCode(code)
        }
        setJSON(execute)
      } catch (error) {
        console.error(error)
      }
    }, 1000)
  }

  return (
    <div style={{height:"100vh", overflow:'hidden', display: "flex", flexDirection: "column"}} onKeyDown={haddleKeyDown}>
      <div style={{display:"flex",justifyContent: "space-between", height:48, alignItems: "center", paddingLeft:16, paddingRight:16 }}>
        <div>
          <img src="https://img.alicdn.com/imgextra/i4/O1CN013w2bmQ25WAIha4Hx9_!!6000000007533-55-tps-137-26.svg"></img>
        </div>
        <div>
          <Button onClick={save}>保存</Button>
        </div>
      </div>
      <div style={{display:"flex", flex:1}}>
        <div style={{flex: 1, padding: 15, backgroundColor:'#edeff3'}}>
          <Table table={menu.key} menu={menu.key} auths={menu.auths} schema={json.schema} config={json.config}/>
        </div>
        <div style={{width: '30%'}}>
          <MonacoEditor defaultValue={'module.exports = \n' + JSON.toCode(json.config)}
            width='100%' height='calc(100vh - 40px)' 
            onChange={onchange} 
            onBlur={onchange} 
            theme="vs-dark" 
            defaultLanguage="javascript" 
            options={{
              selectOnLineNumbers:true,
              "autoIndent": true,
              "formatOnPaste": true,
              "formatOnType": true
            }} 
          />
        </div>
      </div>
    </div>
  )
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />)
